//
//  JCClubHomeVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/18.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCClubHomeVC.h"
#import "JCClubFindVC.h"
#import "JCClubMeVC.h"
#import "JCClubEventVC.h"
#import "ClubsSetting.h"
#import "UIScrollView+YFMJRefresh.h"
#import "JCClubApi.h"
#import "JCClubInfoVC.h"
#import "JCReportVC.h"
#import "JCReportMemberVC.h"
#import "JCClubReportHomeVC.h"
#import "JCClubRankListMenuView.h"
#import "YFAlertHelper.h"
#import "MyNavigationViewController.h"
#import "AppDelegate.h"

#define kToolBarLineWidth       45
#define kToolBarLineHeight      3
#define kToolBarViewHeight      33
#define kiPhoneXScrollTop       60
#define kiPhoneScrollTop        40
#define kFuncTionPopWidth       281
#define kFuncTionPopHeight      338

@interface JCClubHomeVC ()<JCClubFindVCDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchViewTop;
@property (weak, nonatomic) IBOutlet UITextField *searchInput;
@property (assign, nonatomic) BOOL isPopKeyBoard;

@property (weak, nonatomic) IBOutlet UIView *toolView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolViewHeight;
@property (strong, nonatomic) UIView *lineView;
@property (weak, nonatomic) IBOutlet UIButton *findButton;
@property (weak, nonatomic) IBOutlet UIButton *meButton;
@property (weak, nonatomic) IBOutlet UIButton *eventButton;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *toolButtons;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTop;

@property (weak, nonatomic) IBOutlet UIView *leftView;
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet UIView *rightView;
@property (strong, nonatomic) JCClubFindVC *findVC;
@property (strong, nonatomic) JCClubMeVC *meVC;
@property (strong, nonatomic) JCClubEventVC *eventVC;
@property (strong, nonatomic) JCClubInfoVC *infoVC;

@property (assign, nonatomic) ClubMemberRankType rankType;
@property (assign, nonatomic) ClubMemberRankTimeType timeType;

@end

@implementation JCClubHomeVC {
    MyNavigationViewController *_navigationVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _navigationVc = (MyNavigationViewController *)self.navigationController;
    [self layoutMeView];
    [self initCode];
    [self reigesterNotification];
    self.navigationItem.title = @"Club";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_searchView.alpha == 1) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self.tabBarController.tabBar setHidden:YES];
    }else{
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self.tabBarController.tabBar setHidden:NO];
    }
    if ([YFUserDefaults isNeedRefreshClubMe]) {
        [self layoutMeView];
        [_eventVC loadData];
    }
    _navigationVc.hiddenSeparationLine = YES;
    if ([YFUserDefaults isShowMe]) {
        [YFUserDefaults saveClubOnMEState:NO];
        [self changeClubPageAction:_meButton];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    _navigationVc.hiddenSeparationLine = NO;
}

- (void)reigesterNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(centerViewControllerChangeNoti:) name:kChangeCenterViewControllerNoti object:nil];
}

- (void)centerViewControllerChangeNoti:(NSNotification *)noti {
    if ([noti.object isEqual:self]) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        _navigationVc.hiddenSeparationLine = NO;
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)layoutMeView{
    __weak typeof(self)weakSelf = self;
    NSString *myClubID = [User getUseInfo].adminClubs.firstObject.clubID?[User getUseInfo].adminClubs.firstObject.clubID:[User getUseInfo].joinClubs.firstObject.clubID;
    if (myClubID) {
        if (_meVC) {
            [_meVC.view removeFromSuperview];
            [_meVC removeFromParentViewController];
            _meVC = nil;
        }
        _infoVC = [[UIStoryboard storyboardWithName:@"Clubs" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([JCClubInfoVC class])];
        _infoVC.clubID = myClubID;
        ClubUserType type = [[User getUseInfo] clubUserType];
        if (type == ClubUserTypeGeneral) {
            _infoVC.watchType = WatchClubTypeMyMemberGeneral;
        }else if (type == ClubUserTypeAdmin) {
            _infoVC.watchType = WatchClubTypeMyMemberAdmin;
        }
        [self addChildViewController:_infoVC];
        _infoVC.view.frame = _centerView.bounds;
        [_centerView addSubview:_infoVC.view];
        
    }else{
        if (_infoVC) {
            [_infoVC.view removeFromSuperview];
            [_infoVC removeFromParentViewController];
            _infoVC = nil;
        }
        _meVC = [[UIStoryboard storyboardWithName:@"Clubs" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([JCClubMeVC class])];
        [self addChildViewController:_meVC];
        _meVC.view.frame = _centerView.bounds;
        [_centerView addSubview:_meVC.view];
        _meVC.joinClubAction = ^{
            [weakSelf changeClubPageAction:weakSelf.findButton];
            [weakSelf.findVC enterSeachPopKeyBoard:NO];
        };
    }
    
    _rankType = ClubMemberRankTypeDuration;
    _timeType = ClubMemberRankTimeTypeThisWeek;
}

- (void)initCode{
    
    __weak typeof(self)weakSelf = self;
    if (kDevice_Is_iPhoneX) {
        _searchViewHeight.constant = kIphoneXNaviHeight;
    }else{
        _searchViewHeight.constant = kIphoneNaviHeight;
    }
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kToolBarLineWidth, kToolBarLineHeight)];
    _lineView.backgroundColor = [UIColor yellowColor];
    _lineView.center = CGPointMake(kYFScreenWidth / 6.0, _toolView.frame.size.height - 1);
    [_toolView addSubview:_lineView];
    
    for (UIViewController *vc in self.childViewControllers) {
        if([vc isKindOfClass:[JCClubFindVC class]]){
            _findVC = (JCClubFindVC *)vc;
            _findVC.delegate = self;
        }else if([vc isKindOfClass:[JCClubMeVC class]]){
            _meVC = (JCClubMeVC *)vc;
            _meVC.joinClubAction = ^{
                [weakSelf changeClubPageAction:weakSelf.findButton];
                [weakSelf.findVC enterSeachPopKeyBoard:NO];
            };
        }else if([vc isKindOfClass:[JCClubEventVC class]]){
            _eventVC = (JCClubEventVC *)vc;
            _eventVC.joinClubAction = ^{
                [weakSelf changeClubPageAction:weakSelf.findButton];
                [weakSelf.findVC enterSeachPopKeyBoard:NO];
            };
        }
    }
    _searchInput.attributedPlaceholder = [self creatAttributedString:@"Search club name or club ID" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    
    UIBarButtonItem *reportItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"club_search"] style:UIBarButtonItemStyleDone target:self action:@selector(reportAction:)];
    self.navigationItem.rightBarButtonItem = reportItem;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([[User getUseInfo] clubUserType] == ClubUserTypeAdmin ||
            [[User getUseInfo] clubUserType] == ClubUserTypeGeneral) {
            [self changeClubPageAction:_meButton];
        }
    });
}

- (void)reportAction:(UIBarButtonItem *)sender{
    if ([[User getUseInfo] clubUserType] == ClubUserTypeVisitor) {
        
        [self performSegueWithIdentifier:kSegueClubPushYKReport sender:nil];
    }else if([[User getUseInfo] clubUserType] == ClubUserTypeAdmin){
        
        JCReportMemberVC *reportMemberVC = [[UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([JCReportMemberVC class])];
        reportMemberVC.clubID = [User getUseInfo].adminClubs.firstObject.clubID;
        reportMemberVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:reportMemberVC animated:YES];
    }else if([[User getUseInfo] clubUserType] == ClubUserTypeGeneral){
        JCReportVC *reportVC = [[UIStoryboard storyboardWithName:@"ClubsExtension" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([JCReportVC class])];
        reportVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:reportVC animated:YES];
    }
}

- (IBAction)changeClubPageAction:(UIButton *)sender {
    NSInteger index = 0;
    if (sender == _findButton) {
        index = 0;
        [_findVC showView];
    }else if (sender == _meButton) {
        index = 1;
    }else if (sender == _eventButton) {
        index = 2;
    }
    for (UIButton *button in _toolButtons) {
        button.selected = NO;
    }
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        sender.selected = YES;
        _lineView.center = CGPointMake(sender.center.x, _toolView.bounds.size.height - 1);
        [_scrollView setContentOffset:CGPointMake(kYFScreenWidth * index, 0) animated:YES];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)didTapSearchAction:(JCClubFindVC *)viewController popKeyBoard:(BOOL)popKeyBoard{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    _scrollViewTop.constant = kDevice_Is_iPhoneX?kiPhoneXScrollTop:kiPhoneScrollTop;
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        _toolViewHeight.constant = 0;
        _toolView.alpha = 0;
        _searchView.alpha = 1;
        [self.view layoutSubviews];
    } completion:^(BOOL finished) {
        if (popKeyBoard) {
            [_searchInput becomeFirstResponder];
        }
    }];
}

- (void)refreashSearchAction:(JCClubFindVC *)viewController result:(void(^)(BOOL success))result {
    [self searchClubsWithText:self.searchInput.text andResult:^(BOOL success, NSArray<JCClubModel *> *resultClubs) {
        if (result) {
            result(success);
        }
    }];
}

- (IBAction)quitSearchAction:(UIButton *)sender {
    _searchInput.text = @"";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    _scrollViewTop.constant = 0;
    [_findVC quitSearch];
    [_searchInput resignFirstResponder];
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        _toolViewHeight.constant = kToolBarViewHeight;
        _toolView.alpha = 1;
        _searchView.alpha = 0;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
       
    }];
}

- (IBAction)searchFunctionAction:(UIButton *)sender {
    [_searchInput resignFirstResponder];
    __weak typeof(self)weakSelf = self;
    JCClubRankListMenuView *alertView = [[UINib nibWithNibName:NSStringFromClass([JCClubRankListMenuView class]) bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    alertView.isSearchPopView = YES;
    [alertView setupInitTimeType:_timeType rankType:_rankType];
    PopupViewController *popVC = [YFAlertHelper showPresentInView:nil alertView:alertView withAlertViewFrame:CGRectMake(0, 0, kFuncTionPopWidth, kFuncTionPopHeight) animationType:DetailViewControllerPresentAnimationTypeDown tapMaskViewDismiss:YES];
    __weak typeof(popVC)weakPopVC = popVC;
    alertView.dismissHandle = ^(ClubMemberRankTimeType timeType, ClubMemberRankType type) {
        weakSelf.timeType = timeType;
        weakSelf.rankType = type;
        [weakPopVC dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self searchClubsWithText:textField.text andResult:^(BOOL success, NSArray<JCClubModel *> *resultClubs) {
            
        }];
        [textField resignFirstResponder];
//      [self quitSearchAction:nil];
        
        self.findVC.searchInputText = textField.text;
        return NO;
    }
    self.findVC.searchInputText = textField.text;
    return YES;
}

- (void)searchClubsWithText:(NSString *)searchText andResult:(void(^)(BOOL success,NSArray<JCClubModel *> *resultClubs))resultBlock {
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi searchClubInfoWithName:searchText complete:^(NSError *error, NSArray<JCClubModel *> *resultClubs) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            if (resultBlock) {
                resultBlock(NO,resultClubs);
            }
        }else{
            [weakSelf.hud dismiss];
            [weakSelf.findVC setSearchResult:resultClubs];
            if (resultBlock) {
                resultBlock(YES,resultClubs);
            }
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    __weak typeof(self)weakSelf = self;
    if ([segue.identifier isEqualToString:kSegueClubPushYKReport]) {
        JCClubReportHomeVC *vc = [segue destinationViewController];
        vc.hidesBottomBarWhenPushed = YES;
        vc.dismissHandle = ^(){
            [weakSelf changeClubPageAction:weakSelf.findButton];
            [weakSelf.findVC enterSeachPopKeyBoard:NO];
        };
    }
}

//- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
//    if ([identifier isEqualToString:@"meEmbed"]) {
//
//    }else{
//        return YES;
//    }
//}

@end
